package valid

import (
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
)

type GroupValid struct {
}

// 添加验证
func (v *GroupValid) ValidAdd(val map[string]interface{}) (bool, string) {
	valid := validation.Validation{}
	vd := valid.Required(val["group_name"], "group_name").Message("名称不能为空")
	if !vd.Ok {
		return false, vd.Error.Message
	}
	ps := getQueryTable("group")
	ext := ps.Filter("group_name", val["group_name"]).Exist()
	if ext {
		return false, "名称已存在"
	}
	return true, ""
}

//修改验证
func (v *GroupValid) ValidEdit(val map[string]interface{}) (bool, string) {
	valid := validation.Validation{}
	vd := valid.Required(val["id"], "id").Message("ID不能为空")
	if !vd.Ok {
		return false, vd.Error.Message
	}
	if val["group_name"] != nil {
		sql := "SELECT id from group where id <> ? and group_name = ? limit 0,1"
		type idExist struct {
			Id int64
		}
		isId := idExist{}
		o := orm.NewOrm()
		_ = o.Raw(sql, val["id"], val["group_name"]).QueryRow(&isId)
		if isId.Id != 0 {
			return false, "名称已存在"
		}
	}
	return true, ""
}
